<template>
  <el-upload
    :action="'#'"
    :http-request="onFileUpload"
    :accept="fileTypes == null ? '' : fileTypes.join(',')"
    :show-file-list="false"
    :disabled="disabled"
    :before-upload="beforeUpload"
    :multiple="true"
  >
    <slot></slot>
  </el-upload>
</template>

<script setup lang="ts">
const props = defineProps({
  action: {
    type: String,
    required: false,
  },
  fileTypes: {
    type: Array,
    default: null,
  },
  maxSize: {
    type: Number,
    default: null,
  },
  showLoading: {
    type: Boolean,
    default: false,
  },
  isPermanent: {
    type: Boolean,
    default: false,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
});
const loading = ref(null) as any;
const uploadHeaders = ref({
  accessToken: sessionStorage.getItem("accessToken"),
});
function onFileUpload(file: any) {
  // 展示加载条
  if (props.showLoading) {
    loading.value = ElLoading.service({
      lock: true,
      text: "正在上传...",
      spinner: "el-icon-loading",
      background: "rgba(0, 0, 0, 0.7)",
    });
  }
  let formData = new FormData();
  formData.append("file", file.file);
  //   this.$http({
  //     url: this.action + "?isPermanent=" + this.isPermanent,
  //     data: formData,
  //     method: "post",
  //     headers: {
  //       "Content-Type": "multipart/form-data",
  //     },
  //   })
  //     .then((data) => {
  //       this.$emit("success", data, file.file);
  //     })
  //     .catch((e) => {
  //       this.$emit("fail", e, file.file);
  //     })
  //     .finally(() => {
  //       this.loading && this.loading.close();
  //     });
}
function beforeUpload(file: any) {
  // 校验文件类型
  if (props.fileTypes && props.fileTypes.length > 0) {
    let fileType = file.type;
    let t = props.fileTypes.find((t: any) => t.toLowerCase() === fileType);
    if (t === undefined) {
      ElMessage.error(
        `文件格式错误，请上传以下格式的文件：${this.fileTypes.join("、")}`
      );
      return false;
    }
  }
  // 校验大小
  if (props.maxSize && file.size > props.maxSize) {
    ElMessage.error(`文件大小不能超过 ${fileSizeStr}!`);
    return false;
  }
  //   this.$emit("before", file);
  return true;
}
const fileSizeStr = computed(() => {
  if (props.maxSize > 1024 * 1024) {
    return Math.round(props.maxSize / 1024 / 1024) + "M";
  }
  if (props.maxSize > 1024) {
    return Math.round(props.maxSize / 1024) + "KB";
  }
  return props.maxSize + "B";
});
</script>

<style lang="scss" scoped></style>
